<template>
  <div class="page">
    <h4 style="margin-left: 12px;">系统账号设置</h4>
    <el-row :gutter="20">
      <el-form ref="formInline" :inline="true" :model="formInline" id="formbox">
        <el-col :span="8">
          <el-form-item label="角色:" prop="roleName" class="mag">
            <el-select v-model="formInline.roleName" placeholder="请选择角色">
              <el-option label="管理员" value="管理员"></el-option>
              <el-option label="普通用户" value="普通用户"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="账号:" prop="userName" class="mag">
            <el-input
              v-model="formInline.userName"
              placeholder="请输入账号"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" class="mb20">
          <el-form-item label="创建时间 :" prop="createTime">
            <el-date-picker
              v-model="formInline.createTime"
              :disabled-date="disableFutureDates"
              type="daterange"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              size="large"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="机构:" prop="institution" class="mag">
            <el-select
              v-model="formInline.institution"
              placeholder="请选择机构"
              @change="handleChange1"
            >
              <el-option
                v-for="option in InstitutionList"
                :label="option"
                :value="option"
                :key="option"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
        <el-form-item label="科室:" prop="department" class="mag1">
          <el-select v-model="formInline.department" placeholder="请选择科室">
            <el-option
              v-for="option in DepartmentList1"
              :label="option"
              :value="option"
              :key="option"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="4">
     
        <el-form-item>
          <el-button type="primary" @click="searchSubmit()">查询</el-button>
          <el-button @click="onReset('formInline')">重置</el-button>
        </el-form-item>
      </el-col>
      </el-form>
    </el-row>
    <el-row class="op">
      <el-col :span="12"
        ><h4>账号列表 (共{{ total }}条)</h4></el-col
      >
      <el-col :span="12" class="tr">
        <el-button type="primary" @click="addUsers">新增</el-button>
      </el-col>
    </el-row>
    <el-empty
      v-if="!tableData.length"
      :image-size="200"
      description="暂无记录"
    ></el-empty>
    <el-row v-else >
      <el-table
        ref="multipleTable"
        border
        :data="tableData"
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="80" align="center" fixed="left" />
        <el-table-column prop="userName" label="账号"align="center"  fixed="left"> </el-table-column>
        <!-- <el-table-column prop="password" label="密码"> </el-table-column> -->
        <el-table-column prop="roleName" label="角色">
          <!-- <template slot-scope="scope">
                <span>{{ scope.row.type !== 1 ? "普通用户" : "管理员" }}</span>
              </template> -->
        </el-table-column>
        <el-table-column prop="institution" label="机构" width="210" align="center">
        </el-table-column>
        <el-table-column prop="department" label="科室" width="120" align="center">
        </el-table-column>
        <el-table-column prop="hisUserName" label="用户" width="120" align="center">
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="180"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="remark"
          label="备注"
          width="180"
          align="center"
        ></el-table-column>
        <el-table-column label="操作" width="300" align="center" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              type="primary"
              size="small"
              @click="handleEdit1(scope.row)"
              >修改密码</el-button
            >
            <!-- v-if="scope.row.type !== 1"  -->
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-col :span="24" style="display: flex; justify-content: end;margin-bottom: 50px;">
      <el-pagination
        v-model:currentPage="this.page"
        v-model:page-size="this.size"
        :total="this.total"
        :page-sizes="[10, 20, 50, 100, 500]"
        class="new-pagination"
        small
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </el-col>
    <el-dialog :title="dialogType" v-model="dialogFormVisible" @close="handleClose">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item
          label="角色"
          prop="roleName"
          :label-width="formLabelWidth"
          placeholder="请选择角色"
          class="add_dialog"
        >
          <!-- <template #label> <span style="color: red">*</span>角色</template> -->
          <!-- <el-input v-model="form.name" autocomplete="off"></el-input> -->
          <el-select v-model="form.roleName" placeholder="请选择角色">
            <el-option label="管理员" value="管理员"></el-option>
            <el-option label="普通用户" value="普通用户"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="账号" :label-width="formLabelWidth">
          <template #label> <span style="color: red">*</span>账号</template>
          <el-input
            v-model="form.userName"
            autocomplete="off"
            placeholder="请输入账号"
            :disabled="dialogType == '编辑' ? true : false"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          :label-width="formLabelWidth"
          v-show="dialogType == '新增' ? true : false"
        >
          <template #label> <span style="color: red">*</span>密码</template>
          <el-input
            v-model="form.password"
            autocomplete="off"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="机构"
          :label-width="formLabelWidth"
          class="add_dialog"
        >
          <template #label> <span style="color: red">*</span>机构</template>
          <el-select
            v-model="form.institution"
            placeholder="请选择机构"
            @change="handleChange"
            :disabled="dialogType == '编辑' ? true : false"
          >
            <el-option
              v-for="option in InstitutionList"
              :label="option"
              :value="option"
              :key="option"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="科室"
          :label-width="formLabelWidth"
          class="add_dialog"
        >
          <template #label> <span style="color: red">*</span>科室</template>
          <el-select
            ref="Depar"
            v-model="form.department"
            placeholder="请选择科室"
            @change="handleChange2"
            :disabled="dialogType == '编辑' ? true : false"
          >
            <el-option
              v-for="option1 in DepartmentList"
              :label="option1"
              :value="option1"
              :key="option1"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="用户"
          :label-width="formLabelWidth"
          class="add_dialog"
        >
          <template #label> <span style="color: red">*</span>用户</template>
          <el-select
            v-model="form.hisUserName"
            placeholder="请选择用户"
            :disabled="dialogType == '编辑' ? true : false"
            @change="handleChange3"
          >
            <el-option
              v-for="option2 in user"
              :label="option2.hisUserName"
              :value="option2.id"
              :key="option2.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input
            v-model="form.remark"
            autocomplete="off"
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
        <div class="tip" v-show="dialogType == '新增'">
          <span>注:无未绑定的HIS用户时，请在HIS账号管理中新增</span>
        </div>
      </el-form>
      <div slot="footer" class="dialog_footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="dialogType" v-model="PasswordChangeFormVisible">
      <el-form :model="PasswordChangeForm">
        <el-form-item label="新密码" :label-width="formLabelWidth">
          <template #label> <span style="color: red">*</span>新密码</template>
          <el-input
            v-model="PasswordChangeForm.lodPassword"
            autocomplete="off"
            placeholder="请输入新密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" :label-width="formLabelWidth">
          <template #label> <span style="color: red">*</span>确认密码</template>
          <el-input
            v-model="PasswordChangeForm.newPassword"
            autocomplete="off"
            placeholder="请再次输入新密码"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog_footer">
        <el-button @click="PasswordChangeFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handPassword()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// import {ElMessage } from "element-ui";
import { ElMessage } from "element-plus";
import http from "@/utils/request";
import { stringifyQuery } from "vue-router";
const disableFutureDates = (time) =>  time > new Date();
export default {
  name: "UsersPage",
  // async asyncData({ $axios }) {
  //   const ip = await $axios.$get('https://www.kuaidi100.com/query?type=yuantong&postid=11111111111')
  //   return { ip }
  // },
  data() {
    const validture = (rule, value, callback) => {
      if (value !== "") {
        callback();
      } else {
        callback(new Error("此项为必填"));
      }
    };
    return {
      PasswordChangeFormVisible: false,
      dialogFormVisible: false,
      PasswordChangeForm: {
        id: "",
        lodPassword: "",
        newPassword: "",
        userName: "",
      },
      formInline: {
        // 角色
        roleName: "",
        userName: "",
        createTime: "",
        startTime: "",
        endTime: "",

        // 机构
        institution: "",
        // 科室
        department: "",
        // 绑定HIS账号id
        hisAccountId: "",
        remark: "",
      },
      dialogType: "新增",
      people: null,
      formLabelWidth: "120px",
      formLabelWidth1: "150px",
      form: {
        // 角色
        roleName: "",
        userName: "",
        password: "",
        createTime: "",
        endTime: "",
        // 机构
        institution: "",
        // 科室
        department: "",
        // 绑定HIS账号id
        hisAccountId: "",
        remark: "",
        hisUserName: "",
      },
      rules: {
        roleName: [{ required: true, validator: validture, trigger: "blur" }],
        userName: [{ required: true, validator: validture, trigger: "blur" }],
        password: [{ required: true, validator: validture, trigger: "blur" }],
        // 机构
        institution: [
          { required: true, validator: validture, trigger: "blur" },
        ],
        // 科室
        department: [{ required: true, validator: validture, trigger: "blur" }],
        // 绑定HIS账号id
        hisUserName: [
          { required: true, validator: validture, trigger: "blur" },
        ],
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7; // 返回true表示禁用，false表示可选
        },
      },
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
      tableData: [
        {
          id: "001",
          userName: "陈磊1",
          password: "abcd1234",
          roleName: "管理员",
          createTime: "2024-02-02 09:09:00",
          updateTime: "2024-02-02 09:09:00",
          status: true,
        },
      ],
      // renderData: [],
      page: 1,
      size: 10,
      total: 0,
      InstitutionList: [],
      DepartmentList1: [],
      DepartmentList: [],
      user: [],
      jg: "",
      hisAccountId: "",
    };
  },
  mounted() {
    this.getUsers();
    // this.getHislist();
    this.getInstitutionList();
  },
  methods: {
    disableFutureDates,
    handleClose(){
    this.DepartmentList1=[];
    this.DepartmentList=[];
    this.user=[];
    },

    handleChange3(value) {
      this.form.hisAccountId = value;
    },
    handleEdit1(row) {
      console.log(row);
      (this.PasswordChangeForm = {
        id: row.id,
        lodPassword: "",
        newPassword: "",
        userName: row.userName,
      }),
        (this.dialogType = "修改密码");
      this.PasswordChangeFormVisible = true;
    },
    handPassword() {
      const { id, lodPassword, newPassword, userName } =
        this.PasswordChangeForm;
      if (!lodPassword && !newPassword) {
        return ElMessage.error("请完整填写表单");
      }
      if (lodPassword != newPassword) {
        return ElMessage.error("两次密码输入不一致");
      }
      // const lopassword = btoa(lodPassword);
      http
        .post("/admin/sysUser/updatePassWord", {
          // userName,
          id,
          newPassword,
          resetPassword: lodPassword,
        })
        .then((res) => {
          if (res.code == 200) {
            ElMessage.success(res.message);
          this.PasswordChangeFormVisible = false;
          this.getUsers();
          }
        });
    },
    onBack() {
      window.location.href = "/";
    },

    handleChange(value) {
      this.jg = value;
      this.form.department = "";
      http
        .post(
          "/admin/sysUser/getDepartmentList",
        {
            institution: value,
          }
        )
        .then((res) => {
          this.DepartmentList = res.data;
        });
    },
    handleChange2(value) {
      this.form.hisUserName="",
      http
        .post("/admin/sysUser/getHisUserList", {
          institution: this.jg,
          department: value,
        })
        .then((res) => {
          if(res.code==200){
            this.user = res.data;
            console.log(res.data); 
          }
        
          
          // this.form.hisAccountId=res.data.data[0].hisAccountId;
        });
    },
    handleChange1(value) {
      this.formInline.department = "";
      http
        .post(
          "/admin/sysUser/getDepartmentList",
        {
            institution: value,
          }
        )
        .then((res) => {
          if(res.code=200){
            this.DepartmentList1 = res.data
          }
         ;
        });
    },

    onSubmit() {
      const { password, institution, department, roleName, userName } = this.form;
      const hisUserName = this.user.find(
        (item) => (item.hisAccountId = this.form.hisAccountId)
      );
      console.log(hisUserName);
      if(hisUserName){
          this.form.hisUserName=hisUserName.hisUserName
        }
      if (!roleName) {
        returnElMessage.error("请完整填写表单");
      }
      // this.form.password = btoa(this.form.password);
      if (this.form?.id) {
        delete this.form.hisAccountId;
        http.post("/admin/sysUser/updateUser", this.form).then((res) => {
          if(res.code==200){
            this.dialogFormVisible = false;
         ElMessage.success(res.message);
          this.getUsers();
          }
        
        });
      } else {
        delete this.form.hisAccountId;
        http.post("/admin/sysUser/addUser", this.form).then((res) => {
          if(res.code==200){
            this.dialogFormVisible = false;
         ElMessage.success(res.message);
          this.getUsers();
          } 
        });
      }
    },
    searchSubmit() {
      this.getUsers();
    },
    getUsers() {
      const requestData = { page: this.page, size: this.size };
      for (const key in this.formInline) {
        if (this.formInline[key]) {
          requestData[key] = this.formInline[key];
          if(key=='createTime'){
          this.formInline.endTime=this.formInline.createTime[1];
          this.formInline.startTime=this.formInline.createTime[0];    
          }
        }
      }
      delete requestData.createTime;
      http.post("/admin/sysUser/getPageList", requestData).then((res) => {
        this.tableData = res.data.list;
        this.total = res.data.total;
      });
    },
    getHislist() {
      http.post("/admin/sysUser/getHisUserList").then((res) => {
        this.user = res.data;
        console.log(res.data);
        
      });
    },
    getInstitutionList() {
      http.post("/admin/sysUser/getInstitutionList").then((res) => {
        this.InstitutionList = res.data;
      });
    },
    getDepartmentList() {
      http.post("/admin/sysUser/getDepartmentList").then((res) => {
        this.DepartmentList = res.data;
      });
    },
    onReset(formName) {
      this.$refs[formName].resetFields();
      this.DepartmentList1 = [];
      this.formInline.endTime="";
      this.formInline.startTime=""; 
    },
    handleSizeChange(val) {
      this.size = val;
      this.page = 1;
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
    },
    addUsers() {
      this.form = {
        // name: "",
        password: "",
      };
      this.dialogType = "新增";
      this.dialogFormVisible = true;
    },
    handleEdit(index, row) {
      console.log(row);
      this.form = {...row};
      this.dialogType = "编辑";
      this.dialogFormVisible = true;
    },
    handleDelete(index, row) {
      // ElMessageBox.confirm(`是否删除该用户: ${row.userName}`, "提示", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning",
      // }).then(() => {

      // });
      this.$confirm(`是否删除该用户: ${row.userName}`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (row.role == 2) {
           ElMessage.error("管理员不能删除");
          } else {
            // const requestData = { id: row.id, hisAccountId: row.hisAccountId };
            const requestData = {id: row.id};
            http.post("/admin/sysUser/removeById",requestData).then((res) => {
              if (res.code == 200) {
                ElMessage.success(res.message);
                this.getUsers();
              } 
              this.dialogFormVisible = false;
         
            });
          }
        })
        .catch(() => {
          // 用户点击取消后执行的逻辑，这里不需要额外操作
        });
      // this.dialogFormVisible = true;
    },
    goto(url) {
      window.location.href = url;
    },
    // getNewDate(newV) {
    //   if (this.tableData.length > 0) {
    //     const v = newV;
    //     const newDate = this.tableData.slice(
    //       (v - 1) * this.size,
    //       v * this.size
    //     );
    //     this.renderData = newDate;

    //     console.log(newDate);
    //   }
    // },
  },

  watch: {
    page: {
      handler: function (newV) {
        this.getUsers();

      },
    },
    size: {
      handler: function () {
        this.getUsers();
      },
    },
    formInline: {
      deep: true,
      handler: function () {
        // console.log(this.formInline);
      },
    },
  },
};
</script>
<style scoped lang="scss">
.el-table th.is-center,
.el-table td.is-center {
  text-align: center !important;
}
.page {
  padding: 10px 20px;
  width: 100%;
  box-sizing: border-box;
}
#formbox {
  display: flex;
  flex-wrap: wrap;
  padding: 0 30px;
}
.dialog_footer {
  margin-top: 20px;
  display: flex;
  justify-content: end;
}
.add_dialog {
  :deep(.el-select .el-select__wrapper) {
    min-height: 32px;
    width: 100% !important;
  }
}
:deep(.el-input__wrapper) {
  width: 230px;
}
:deep(.el-form-item .el-select__wrapper) {
  min-height: 32px;
  width: 252px;
}
:deep(.el-range-editor--large.el-input__wrapper) {
  height: 32px;
  width: 252px;
}
.form-button {
  display: flex;
  justify-content: start;
}
.table-container {
  display: flex;
  flex-direction: column;
}
.table-btn {
  display: flex;
  height: 50px;
  align-items: center;
  justify-content: space-around;
}
.tr {
  text-align: right;
  height: 50px;
  line-height: 50px;
}
::v-deep .all-disabled .el-checkbox__input .el-checkbox__inner {
  display: none;
}

.new-pagination {
  margin: 30px 0 10px 0 !important;
}
.required:before {
  content: "*";
  color: red;
  margin-right: 5px;
}

.box {
  display: flex;
  margin-right: 30px;
}
h1 {
  font-size: 14px;
  text-align: left;
  padding: 0;
}
h2 {
  font-size: 18px;
}
h3 {
  margin: 0;
}

.main-top {
  height: 50px;
  text-align: right;
  border-bottom: 1px solid #f1f1f1;
}
.main-top .el-button {
  height: 50px;
  width: 120px;
  font-size: 20px;
}
.main-filter {
  padding: 0 20px;
  border-bottom: 1px solid #f1f1f1;
}
.op {
  padding: 20px;
}
.op h4 {
  margin: 0;
  padding: 0;
}
.tr {
  text-align: right;
}
.tb {
  padding: 0 20px;
  overflow-y: scroll;
}
.el-menu-item-group__title {
  display: none;
}
.demo-form-inline {
  display: flex;
  flex-wrap: wrap;
}
.mag {
  margin-right: 60px !important;
}
.mag1 {
  margin-right: 72px !important;
}
.mag2 {
  margin-right: 162px !important;
}
.input_height {
  height: 70px !important;
}
.tip {
  color: red;
  font-size: 12px;
  margin-left: 90px;
}
.demo-form-inline {
  display: flex;
  flex-wrap: wrap;
  width: 70vw;
}
</style>
